package handel

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"net/http"
	"post-master/cache"
	"post-master/model"
	"time"
)

func Add(c *gin.Context) {

	title := c.PostForm("title")
	desc := c.PostForm("desc")
	author := c.PostForm("author")

	if title == "" || desc == "" || author == "" {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "字段不可为空",
		})
		return
	}

	data := model.Article{
		Title:  title,
		Desc:   desc,
		Author: author,
	}
	err := model.DB.Debug().Create(&data).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "数据添加失败",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "成功",
	})
	return

}

func Del(c *gin.Context) {
	id := c.PostForm("id")

	err := model.DB.Debug().Where("id=?", id).Delete(&model.Article{}).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "删除失败",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return

}

func List(c *gin.Context) {
	var articles []model.Article
	redis_key := "redis_list"
	result, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if result == "" {
		model.DB.Debug().Find(&articles)
		jsonData, _ := json.Marshal(articles)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)

	} else {
		json.Unmarshal([]byte(result), &articles)
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "成功",
		"data": articles,
	})
	return
	
}
